<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script type="text/javascript">
    window.onload=function (){
      var checkButton = document.getElementById("checkButton");
      checkButton.onclick=function (){
        //1.创建XMLHttpRequest对象
        var xhr = new XMLHttpRequest();
        var value = document.getElementById("uname").value;
        // alert(value)
        //2.(1)准备发送的数据open
        //(2)这里?后面是什么，servlet端就用什么来接收
        //如:String uname = request.getParameter("uname");
        //(3)true表示异步发送
        xhr.open("GET","/ajax/checkUserServlet?username="+value,true)
        //3.真正发送请求
        //给XMLHttpRequest绑定一个事件onreadystatechange
        //当数据发生变化时，就会触发onreadystatechange
        //每当xhr对象readyState改变时，就会触发onreadystatechange事件
        xhr.onreadystatechange=function (){
          console.log(xhr)
          //如果请求已完成，且响应已就绪(4)，并且状态码是200
          if(xhr.readyState==4&&xhr.status==200){
              var responseText = xhr.responseText;
              if(responseText!=""){
                document.getElementById("myres").value="用户不可用"
              }else{
                document.getElementById("myres").value="用户可用"
              }
          }
        }
        xhr.send();
      }
    }
  </script>
</head>
<body>
<h1>用户注册~</h1>
<form action="/ajax/checkUserServlet" method="post">
  用户名字:<input type="text" name="username" id="uname">
  <input type="button" id="checkButton" value="验证用户名">
  <input style="border-width: 0;color: red" type="text" id="myres"><br/><br/>
  用户密码:<input type="password" name="password"><br/><br/>
  电子邮件:<input type="text" name="email"><br/><br/>
  <input type="submit" value="用户注册">
</form>
<h1>返回的json数据</h1>
<div id="div1"></div>
</body>
</html>